/**
 * Copyright(c) kyle.
 */
package org.example.metrics;

import com.codahale.metrics.*;

import java.sql.Time;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

import static java.util.concurrent.ThreadLocalRandom.current;

/**
 * RatioGaugeExample按照比率记录
 *
 * @author kyle
 * @version 1.00.00
 * @updateUser [Kyle]
 * @updateRemark [说明本次修改内容]
 * @date [2021-09-21 12:51]
 * @since [2021-09-21 12:51]
 */
public class RatioGaugeExample {
    public static final MetricRegistry registry = new MetricRegistry();
    public static final Meter totalMeter = new Meter();
    public static final Meter successMeter = new Meter();
    public static final //定义运行的相关参数
            ConsoleReporter reporter = ConsoleReporter.forRegistry(registry)
            .convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.SECONDS)
            .build();


    public static void main(String[] args) {
        reporter.start(10, TimeUnit.SECONDS);
        registry.gauge("success-rate",()->new RatioGauge() {
            @Override
            protected Ratio getRatio() {
                return Ratio.of(successMeter.getCount(),totalMeter.getCount());
            }
        });
        while (true){
            randomSleep();
            business();
        }
    }

    private static void business() {
        totalMeter.mark();
        try {
            int x=10/current().nextInt(6);
            successMeter.mark();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void randomSleep() {
        try {
            TimeUnit.SECONDS.sleep(current().nextInt(6));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
